package com.ruoyi.system.service.impl;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.ruoyi.system.domain.SapData;
import com.ruoyi.system.https.bo.ZMES_GET_PWOQA_REPONSE;
import com.ruoyi.system.https.bo.ZWS_PP_GET_PWOI_RESPONSE;
import com.ruoyi.system.https.vo.ZMES_GET_PWOQA_REQUEST;
import com.ruoyi.system.https.vo.ZWS_PP_GET_PWOI_REQUEST;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.OrderqaInfoMapper;
import com.ruoyi.system.domain.OrderqaInfo;
import com.ruoyi.system.service.IOrderqaInfoService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-12
 */
@Service
public class OrderqaInfoServiceImpl extends ServiceImpl<OrderqaInfoMapper,OrderqaInfo>implements IOrderqaInfoService
{
    @Autowired
    private OrderqaInfoMapper orderqaInfoMapper;
    @Value("${sap.ZMES_GET_PWOQA.url}")
    private String ZMES_GET_PWOQA_Url;
    @Value("${sap.ZMES_GET_PWOQA.SOAPAction}")
    private String ZMES_GET_PWOQA_SOAPAction;
    @Value("${sap.auth.user}")
    private String user;
    @Value("${sap.auth.password}")
    private String password;
    @Autowired
    ExternalApiService externalApiService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public OrderqaInfo selectOrderqaInfoById(Long id)
    {
        return orderqaInfoMapper.selectOrderqaInfoById(id);
    }

    @Override
    public List<OrderqaInfo> getOrderQaFromOrderNo(String orderNo) {
        LambdaQueryWrapper<OrderqaInfo> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(OrderqaInfo::getOrderNo,orderNo);
        wrapper.eq(OrderqaInfo::getIsEnable,1);
        return baseMapper.selectList(wrapper);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param orderqaInfo 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<OrderqaInfo> selectOrderqaInfoList(OrderqaInfo orderqaInfo,Integer pageNum,Integer pageSize)
    {
        LambdaQueryWrapper<OrderqaInfo> lambdaQueryWrapper =new LambdaQueryWrapper();
        if(StringUtils.isNotBlank(orderqaInfo.getOrderNo())){
            lambdaQueryWrapper.eq(OrderqaInfo::getOrderNo,orderqaInfo.getOrderNo());
        }
        if(StringUtils.isNotBlank(orderqaInfo.getMaterial())){
            lambdaQueryWrapper.eq(OrderqaInfo::getMaterial,orderqaInfo.getMaterial());
        }
        if(StringUtils.isNotBlank(orderqaInfo.getMaterialDesc())){
            lambdaQueryWrapper.eq(OrderqaInfo::getMaterialDesc,orderqaInfo.getMaterialDesc());
        }
        if(StringUtils.isNotBlank(orderqaInfo.getPlant())){
            lambdaQueryWrapper.eq(OrderqaInfo::getPlant,orderqaInfo.getPlant());
        }
        if(StringUtils.isNotBlank(orderqaInfo.getItemSpec())){
            lambdaQueryWrapper.eq(OrderqaInfo::getItemSpec,orderqaInfo.getItemSpec());
        }

        return baseMapper.selectPage(new Page<>(pageNum,pageSize),lambdaQueryWrapper).getRecords();
    }

    @Override
    public Long selectOrderqaInfoCount(OrderqaInfo orderqaInfo) {
        LambdaQueryWrapper<OrderqaInfo> lambdaQueryWrapper =new LambdaQueryWrapper();
        if(StringUtils.isNotBlank(orderqaInfo.getOrderNo())){
            lambdaQueryWrapper.eq(OrderqaInfo::getOrderNo,orderqaInfo.getOrderNo());
        }
        if(StringUtils.isNotBlank(orderqaInfo.getMaterial())){
            lambdaQueryWrapper.eq(OrderqaInfo::getMaterial,orderqaInfo.getMaterial());
        }
        if(StringUtils.isNotBlank(orderqaInfo.getMaterialDesc())){
            lambdaQueryWrapper.eq(OrderqaInfo::getMaterialDesc,orderqaInfo.getMaterialDesc());
        }
        if(StringUtils.isNotBlank(orderqaInfo.getPlant())){
            lambdaQueryWrapper.eq(OrderqaInfo::getPlant,orderqaInfo.getPlant());
        }
        if(StringUtils.isNotBlank(orderqaInfo.getItemSpec())){
            lambdaQueryWrapper.eq(OrderqaInfo::getItemSpec,orderqaInfo.getItemSpec());
        }
        return baseMapper.selectCount(lambdaQueryWrapper);
    }

    @Override
    public List<OrderqaInfo> selectOrderqaInfoAll(OrderqaInfo orderqaInfo)
    {
        return orderqaInfoMapper.selectOrderqaInfoList(orderqaInfo);
    }
    /**
     * 新增【请填写功能名称】
     *
     * @param orderqaInfo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertOrderqaInfo(OrderqaInfo orderqaInfo)
    {
        return orderqaInfoMapper.insertOrderqaInfo(orderqaInfo);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param orderqaInfo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateOrderqaInfo(OrderqaInfo orderqaInfo)
    {
        return orderqaInfoMapper.updateOrderqaInfo(orderqaInfo);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteOrderqaInfoByIds(Long[] ids)
    {
        return orderqaInfoMapper.deleteOrderqaInfoByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteOrderqaInfoById(Long id)
    {
        return orderqaInfoMapper.deleteOrderqaInfoById(id);
    }

    @Override
    public boolean updateOrderqaInfoBySap(String orderNo, String userId) throws JsonProcessingException {
        //查询表中已有该单号数据所有字段
        List<OrderqaInfo> localOrderqaInfo=selectByOrderNo(orderNo);
        //再通过ZWS_PP_GET_PWOI接口从 sap 获取数据;
        //组装body
        ZMES_GET_PWOQA_REQUEST.Item item=new ZMES_GET_PWOQA_REQUEST.Item();
        ZMES_GET_PWOQA_REQUEST.Pwoqa pwoqa=new ZMES_GET_PWOQA_REQUEST.Pwoqa();
        pwoqa.setItem(item);
        ZMES_GET_PWOQA_REQUEST.ZmesGetPwoqa zmesGetPwoqa=new ZMES_GET_PWOQA_REQUEST.ZmesGetPwoqa();
        zmesGetPwoqa.setOrderNo(orderNo);
        zmesGetPwoqa.setPwoqa(pwoqa);
        ZMES_GET_PWOQA_REQUEST.SoapBody soapBody=new ZMES_GET_PWOQA_REQUEST.SoapBody();
        soapBody.setZmesGetPwoqa(zmesGetPwoqa);
        ZMES_GET_PWOQA_REQUEST zmesGetPwoqaRequest=new ZMES_GET_PWOQA_REQUEST();
        zmesGetPwoqaRequest.setBody(soapBody);
        //转成xml
        XmlMapper xmlMapper=new XmlMapper();
        ObjectWriter objectWriter=xmlMapper.writerWithDefaultPrettyPrinter();
        String xml = objectWriter.writeValueAsString(zmesGetPwoqaRequest);
        //设置请求头的额外参数
        //添加SOAPAction
        Map<String,String> headerParamsMap=new HashMap<>();
        headerParamsMap.put("Content-Type", "text/xml;charset=UTF-8");
        headerParamsMap.put("Accept", "text/xml");
        headerParamsMap.put("User_Agent","Apache-HttpClient/4.5.5 (Java/17.0.12)");
        headerParamsMap.put("Accept_Encoding","gzip,deflate");
        headerParamsMap.put("Content_Length","1074");
        headerParamsMap.put("Host","s4suitedevapp.nipponpaint.com.sg:8200");
        headerParamsMap.put("Connection","Keep-Alive");
        if(StringUtils.isNotBlank(ZMES_GET_PWOQA_SOAPAction)) {
            headerParamsMap.put("SOAPAction", ZMES_GET_PWOQA_SOAPAction);
        }
        // 添加基本认证信息
        if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password)) {
            String auth = user + ":" + password; // 替换为你的用户名和密码
            byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
            String authHeader = "Basic " + new String(encodedAuth);
            headerParamsMap.put("Authorization", authHeader);
        }
        //发送请求
        ZMES_GET_PWOQA_REPONSE zmesGetPwoqaReponse=externalApiService.callExternalApi(ZMES_GET_PWOQA_Url, HttpMethod.POST, headerParamsMap,null,xml, ZMES_GET_PWOQA_REPONSE.class);
        return dealResponse(localOrderqaInfo ,zmesGetPwoqaReponse);
    }

    public List<OrderqaInfo> selectByOrderNo(String orderNo) {
        LambdaQueryWrapper<OrderqaInfo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(OrderqaInfo::getOrderNo, orderNo);
        wrapper.eq(OrderqaInfo::getIsEnable,1);
        return this.list(wrapper);
    }
    @Transactional(rollbackFor = Exception.class)
    public boolean dealResponse(List<OrderqaInfo> localOrderqaInfos ,ZMES_GET_PWOQA_REPONSE zmesGetPwoqaReponse){
        int flage=-1;
        if(zmesGetPwoqaReponse==null){
            return false;
        }else {
            //接口返回结果映射为OrderqaInfo对象
            List<OrderqaInfo> orderqaInfoList = ZMES_GET_PWOQA_REPONSE.bodyToOrderqaInfo(zmesGetPwoqaReponse);
            //数据对比
            //数量对比
            if (localOrderqaInfos.size() != orderqaInfoList.size()) {
                //数量不一致，更新数据状态
                Set<Long> Ids = localOrderqaInfos.stream().map(OrderqaInfo::getId).collect(Collectors.toSet());
                if(Ids.size()>0) {
                    flage = updateOrderqaInfoStatusBatch(Ids, 0);
                }
                if (flage == -1||flage>0) {
                    //更新成功，插入新数据
                    insertOrderqaInfoBatch(orderqaInfoList);
                    return true;
                } else {
                    return false;
                }
            } else {
                //数量一致，对比数据
                int[] flag = new int[orderqaInfoList.size()];
                for (int i = 0; i < orderqaInfoList.size(); i++) {
                    int k = 0;
                    for (int j = 0; j < localOrderqaInfos.size(); j++) {
                        //确定同一条数据
                        if (localOrderqaInfos.get(i).getOrderNo().equals(orderqaInfoList.get(j).getOrderNo())
                                && localOrderqaInfos.get(i).getMaterial().equals(orderqaInfoList.get(j).getMaterial())
                                && localOrderqaInfos.get(i).getItemSpec().equals(orderqaInfoList.get(j).getItemSpec())) {
                            flag[j] = 1;
                            //判断数据是否一致
                            if (localOrderqaInfos.get(i).equals(orderqaInfoList.get(j))) {
                                //数据一致，跳过
                                break;
                            } else {
                                //数据不一致，更新数据
                                localOrderqaInfos.get(i).setIsEnable(0l);
                                updateOrderqaInfoData(localOrderqaInfos.get(i));
                                insertOrderqaInfoData(orderqaInfoList.get(j));
//                                orderqaInfoList.get(j).setId(localOrderqaInfos.get(i).getId());
//                                updateOrderqaInfoData(orderqaInfoList.get(j));
                                break;

                            }

                        }
                        k++;
                    }
                    if (k == orderqaInfoList.size()) {
                        //遍历完，没有找到，插入新数据
                        OrderqaInfo orderqaInfo = orderqaInfoList.get(i);
                        orderqaInfo.setIsEnable(1l);
                        insertOrderqaInfoData(orderqaInfo);
                    }
                }
                for (int i = 0; i < flag.length; i++) {
                    if (flag[i] == 0) {
                        //本地数据存在，接口数据不存在。更新状态
                        localOrderqaInfos.get(i).setIsEnable(0l);
                        updateOrderqaInfoData(localOrderqaInfos.get(i));
                    }
                }
            }
            return true;
        }
    }
    //批量修改状态
    public int  updateOrderqaInfoStatusBatch(Set<Long> Ids ,Integer status) {
        LambdaUpdateWrapper<OrderqaInfo> wrapper = new LambdaUpdateWrapper();
        wrapper.in(OrderqaInfo::getId, Ids);
        wrapper.set(OrderqaInfo::getIsEnable, status);//设置状态为0-已删除/旧数据
        return  baseMapper.update(new OrderqaInfo(),wrapper);
    }
    //批量插入
    public boolean insertOrderqaInfoBatch(List<OrderqaInfo> dataList) {
        return saveBatch(dataList);
    }
    public int insertOrderqaInfoData(OrderqaInfo orderqaInfo) {
        return this.baseMapper.insert(orderqaInfo);
    }
    public int updateOrderqaInfoData(OrderqaInfo orderqaInfo) {
        return this.baseMapper.updateById(orderqaInfo);
    }
}
